﻿package com.sff.site.connector {
	import com.sff.core.sff_internal;
	import com.sff.encrypt.Base64;
	import com.sff.site.address.SWFAddress;
	import com.sff.site.address.SWFAddressEvent;
	import com.sff.site.core.IPath;
	import com.sff.site.tree.SiteTree;
	import com.sff.site.tree.SiteTreePath;
	import com.sff.site.tree.TreesProvider;
	
	import flash.events.Event;
	import flash.external.ExternalInterface;
	
	public class SwfAddressConnector extends TreeConnector {

		public static const SEPARATOR : String = ',';

		public function SwfAddressConnector(  ) {
			super();
			
			if( instance != null ) {
				throw new Error( "Call SwfAdressConnector.start() first" );
			}
			
			SWFAddress.setStrict( false );
			SWFAddress.addEventListener( SWFAddressEvent.INIT, onSwfAdressInit );
		}
		
		private function onSwfAdressInit(event : SWFAddressEvent) : void {
			
		}

		sff_internal function connectAddress( ) : void {
			SWFAddress.addEventListener( Event.CHANGE, onAddressChange );
			onAddressChange(null);
		}
		
		override protected function onPathChange( evt : Event ) : void {
			
			var url : String = "";
			var siteTree : SiteTree;
			
			for each ( var deviceId : String in _devices ) {
				siteTree = TreesProvider.sff_internal::getTree( deviceId );
				
				if(siteTree.activePath ) {
					url += getUrlImg(siteTree.activePath );
				}				
				url += SEPARATOR;
			}
			
			url = url.replace(STRIP_PATH, "");
			SWFAddress.setValue( url );
		}


		override protected function deviceAdded(device : String) : void {
			super.deviceAdded( device );
			onAddressChange(null);
		}
		
		private function onAddressChange(evt : Event ) : void {
			
			var paths : Array = SWFAddress.getValue( ).split( SEPARATOR );
			
			while( paths.length > _devices.length ) {
				paths.pop();
			}

			var pLength : int = paths.length;
			var addPath : SiteTreePath;
			
			for (var i : int = 0; i < pLength; i++) {
				addPath = new SiteTreePath( decode( paths[i] ), _devices[ i ] );
				addPath.activate();
			}
			
			for ( i = pLength; i < _devices.length ; i++) {
				addPath = new SiteTreePath( "", _devices[ i ] );
				addPath.activate();
			}			
		}
		
		private function decode(path : String ) : String {
			var sp : Array = path.split( "?p=" );
			if( sp.length > 1 ) 
				return sp[0] + "?" + Base64.decode( sp[1] );
				
			return path;
		}

		private function getUrlImg( path : IPath ) : String {
			if( path.getParams() )
				return path.getPath( ) + "?p=" + Base64.encode( path.getParams().toString() );
			else
				return path.getPath( );
		}

		private static const STRIP_PATH : RegExp = new RegExp( "[,]*$" , "gi" );
		
		
		public static var instance : SwfAddressConnector;

		public static function start( ) : SwfAddressConnector {
			if (instance == null)
				instance = new SwfAddressConnector( );
			return instance;
		}
	}
}
